package com.nvwa.stater.logback.trace;

import com.nvwa.coding.util.trace.TraceHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.web.filter.AbstractRequestLoggingFilter;

import javax.servlet.http.HttpServletRequest;

/**
 * 处理traceId的Filter
 */
@Slf4j
public class MyTraceFilter extends AbstractRequestLoggingFilter implements Ordered {
    @Override
    protected void beforeRequest(HttpServletRequest httpServletRequest, String msg) {
        String traceId = httpServletRequest.getHeader(TraceHolder.TRACE_ID);
        if (traceId == null) {
            traceId = TraceHolder.make();
            httpServletRequest.setAttribute(TraceHolder.TRACE_ID, traceId);
        } else {
            TraceHolder.set(traceId);
        }
        log.debug("==>: {}", msg);
    }

    @Override
    protected void afterRequest(HttpServletRequest httpServletRequest, String msg) {
        log.debug("<==: {}", msg);
        TraceHolder.clear();
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
